package cn.kshost.sqpz.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.kshost.zqyg.model.vo.common.Result;
import cn.kshost.zqyg.model.vo.common.ResultCodeEnum;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class LoginAuthFilter implements GlobalFilter, Ordered {
    private AntPathMatcher matcher = new AntPathMatcher();
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //验证路径是否匹配
        String path = exchange.getRequest().getURI().getPath();
        log.info("path:"+path);
        //如果路径匹配进行拦截
        if (matcher.match("/**/auth/**",path)){
            //获取请求头中token
            List<String> tokenList = exchange.getRequest().getHeaders().get("token");
            if (tokenList != null){
                String token = tokenList.get(0);
                String userInfoJson = redisTemplate.opsForValue().get("user:login:"+token);
                if (StrUtil.isEmpty(userInfoJson)){
                   return   out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH);
                }
            }else {
               return   out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH);
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return-1;
    }
    public static Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        // 设置响应头，避免中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

}
